<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app" :hoverable="true">
      <a-row justify="space-between" style="margin-bottom: 20px">
        <a-col :span="12">
          <a-space :size="20">
            <h3 style="display: inline">电键：{{ data.form.docEntry }}</h3>
            <h3 style="display: inline">名称：{{ data.form.objName }}</h3>
            <h3 style="display: inline">
              状态：
              <a-tag color="#87d068">{{ data.form.docStatus }}</a-tag>
            </h3>
            <h3 style="display: inline">
              审核：
              <a-tag color="#87d068">{{ data.form.approved ? '已审核' : '未审核' }}</a-tag>
            </h3>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-button-group>
              <a-button @click="back()">返回</a-button>
              <a-button @click="save()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || !data.form.edit)"
                >保存
              </a-button>
              <a-button @click="edit()" v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved || data.form.edit)"
                >编辑
              </a-button>
              <a-button @click="del()" v-if="data.form.docStatus === 'O' && !data.form.approved && !data.form.edit">删除</a-button>
              <a-button @click="approved()" v-if="!data.form.edit">查看审核</a-button>
              <a-dropdown>
                <a-button v-if="!(data.form.edit || data.form.docStatus === 'L')"> 更多操作</a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a" v-if="data.form.docStatus !== 'C'">关闭单据</a-menu-item>
                    <a-menu-item key="b" v-if="data.form.docStatus === 'C'">打开单据</a-menu-item>
                    <a-menu-item key="c" v-if="!data.form.approved">发起审核</a-menu-item>
                    <a-menu-item key="d" v-if="data.form.approved">取消审核</a-menu-item>
                    <a-menu-item key="e" v-if="data.form.lista.length === 0 && data.form.listb.length === 0 && data.form.listc.length === 0"
                      >生成细表
                    </a-menu-item>
                    <a-menu-item key="f" v-if="data.form.lista.length !== 0 || data.form.listb.length !== 0 || data.form.listc.length !== 0"
                      >清空细表
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-button @click="refresh" value="7"> 刷 新</a-button>
            </a-button-group>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="formRef" :model="data.form" :rules="data.rules" :label-col="{ span: 5 }">
        <a-row class="smart-query-form-row">
          <a-col :span="6">
            <a-form-item label="月期间" name="absId">
              <a-input v-if="data.form.edit" v-model:value="data.form.absId" />
              <span v-else>{{ data.form.absId }}</span>
            </a-form-item>
            <a-form-item label="部门" name="deptId">
              <DepartmentTreeSelect v-if="data.form.edit" :init="false" v-model:value="data.form.deptId" @update:value="change" />
              <span v-else>{{ data.form.deptName }}</span>
            </a-form-item>
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit" v-model:value="data.form.remark" :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
<!--            <a-form-item label="正常工时">-->
<!--              <span>{{ data.form.workTime }}</span>-->
<!--            </a-form-item>-->
<!--            <a-form-item label="正常费用">-->
<!--              <span>{{ data.form.workCost }}</span>-->
<!--            </a-form-item>-->
<!--            <a-form-item label="加班工时">-->
<!--              <span>{{ data.form.workOverTime }}</span>-->
<!--            </a-form-item>-->
<!--            <a-form-item label="加班费用">-->
<!--              <span>{{ data.form.workOverCost }}</span>-->
<!--            </a-form-item>-->
          </a-col>
          <a-col :span="6">
<!--            <a-form-item label="总工时">-->
<!--              <span>{{ data.form.workTime + data.form.workOverTime }}</span>-->
<!--            </a-form-item>-->
<!--            <a-form-item label="总费用">-->
<!--              <span>{{ data.form.workCost + data.form.workOverCost }}</span>-->
<!--            </a-form-item>-->

          </a-col>
        </a-row>
      </a-form>
      <a-row>
        <a-tabs v-model:activeKey="data.activeKey" style="width: 100%">
          <a-tab-pane key="1" tab="设备汇总">
            <a-table
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }"
              :scroll="{ y: 600, x: 1500 }"
              :dataSource="data.form.lista"
              :columns="columnsa"
              rowKey="lineNum"
            >
              <template #summary>
                <a-table-summary fixed>
                  <a-table-summary-row>
                    <a-table-summary-cell align="right" v-for="(item, index) in columnsa" :key="index" :index="1">
                      <template v-if="item.summary">
                        <a-typography-text>
                          {{ combinedNumsa(item.dataIndex).toFixed(2) }}
                        </a-typography-text>
                      </template>
                    </a-table-summary-cell>
                  </a-table-summary-row>
                </a-table-summary>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="生产汇总">
            <a-table
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }"
              :scroll="{ y: 600, x: 1500 }"
              :dataSource="data.form.listb"
              :columns="columnsb"
              rowKey="lineNum"
            >
              <template #summary>
                <a-table-summary fixed>
                  <a-table-summary-row>
                    <a-table-summary-cell align="right" v-for="(item, index) in columnsb" :key="index" :index="1">
                      <template v-if="item.summary">
                        <a-typography-text>
                          {{ combinedNumsb(item.dataIndex).toFixed(2) }}
                        </a-typography-text>
                      </template>
                    </a-table-summary-cell>
                  </a-table-summary-row>
                </a-table-summary>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="3" tab="非生产汇总">
            <a-table
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                defaultPageSize: 20,
              }"
              :scroll="{ y: 600, x: 1500 }"
              :dataSource="data.form.listc"
              :columns="columnsc"
              rowKey="lineNum"
            >
              <template #summary>
                <a-table-summary fixed>
                  <a-table-summary-row>
                    <a-table-summary-cell align="right" v-for="(item, index) in columnsc" :key="index" :index="1">
                      <template v-if="item.summary">
                        <a-typography-text>
                          {{ combinedNumsc(item.dataIndex).toFixed(2) }}
                        </a-typography-text>
                      </template>
                    </a-table-summary-cell>
                  </a-table-summary-row>
                </a-table-summary>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-row>
    </a-card>
  </a-spin>
  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>
  <MmordList :visible="data.visible.mmord" :on-close="oncloseMmord"></MmordList>
</template>
<script setup>
  import { computed, onMounted, reactive, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { accountaApi, accountApi, accountbApi, accountcApi } from '/@/api/business/erp/account-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { useRouter, useRoute } from 'vue-router';
  import DepartmentTreeSelect from '/@/components/system/department-tree-select/index.vue';

  import { approvordApi } from '/@/api/business/erp/approvord-api';
  import Approvord from '/@/components/business/erp/approved.vue';
  import MmordList from '/@/components/business/erp/mmordList.vue';
  import { nmmordApi } from '/@/api/business/erp/nmmord-api.js';

  // ---------------------------- 表格列 ----------------------------
  const route = useRoute();
  const router = useRouter();
  const data = reactive({
    form: {
      docEntry: 0,
      objId: '',
      absId: '',
      approved: false,
      docStatus: 'O',
      edit: false,
      lista: [],
      listb: [],
      listc: [],
    },
    radioGroup: null,
    rules: {
      absId: [{ required: true, message: '请选择月期间' }],
      deptId: [{ required: true, message: '请选择部门' }],
      batchId: [{ required: true, message: '请输入设备名称' }],
      itemName: [{ required: true, message: '请输入设备地址' }],
    },
    model: {
      absId: '',
    },
    editableData: {
      nowDate: null,
    },
    activeKey: '2',
    visible: {
      mac: false,
      user: false,
      approvord: false,
      mmord: false,
    },
    approvedData: {
      baseEntry: null,
      tabName: null,
    },
  });
  const columnsa = ref([
    {
      title: '行号',
      dataIndex: 'lineNum',
      align: 'center',
      width: 100,
    },
    {
      title: '设备编码',
      dataIndex: 'macId',
      align: 'center',
      width: 100,
    },
    {
      title: '设备名称',
      dataIndex: 'macName',
      align: 'center',
      width: 100,
    },

    {
      title: '时间',
      dataIndex: 'macTime',
      align: 'right',
      width: 100,
      summary: true,
    },
    {
      title: '费用',
      dataIndex: 'macCost',
      align: 'right',
      width: 100,
      summary: true,
    },
    {
      title: '工单编码',
      dataIndex: 'baseEntry',
      align: 'center',
      width: 100,
    },
  ]);
  const columnsb = ref([
    {
      title: '行号',
      dataIndex: 'lineNum',
      align: 'center',
    },
    {
      title: '员工编码',
      dataIndex: 'userId',
      align: 'center',
    },
    {
      title: '员工名称',
      dataIndex: 'userName',
      align: 'center',
    },
    {
      title: '正常',
      dataIndex: 'workTime',
      align: 'right',
      summary: true,
    },

    {
      title: '正常金额',
      dataIndex: 'workCost',
      align: 'right',
      summary: true,
    },

    {
      title: '平常',
      dataIndex: 'common',
      align: 'right',
      summary: true,
    },
    {
      title: '平常金额',
      dataIndex: 'commonCost',
      align: 'right',
      summary: true,
    },

    {
      title: '公休工时',
      dataIndex: 'workOverTime',
      align: 'right',
      summary: true,
    },
    {
      title: '公休金额',
      dataIndex: 'workOverCost',
      align: 'right',
      summary: true,
    },

    {
      title: '节假',
      dataIndex: 'holiday',
      align: 'right',
      summary: true,
    },
    {
      title: '节假金额',
      dataIndex: 'holidayCost',
      align: 'right',
      summary: true,
    },
    {
      title: '调休/旷工',
      dataIndex: 'deduct',
      align: 'right',
      summary: true,
    },
    {
      title: '调休/旷工费用',
      dataIndex: 'deductCost',
      align: 'right',
      summary: true,
      width: 200,
    },

    {
      title: '工单编码',
      dataIndex: 'baseEntry',
      align: 'center',
    },
    {
      title: '行状态',
      dataIndex: 'lineStatus',
      align: 'center',
    },
  ]);
  const columnsc = ref([
    {
      title: '行号',
      dataIndex: 'lineNum',
      align: 'center',
    },
    {
      title: '员工编码',
      dataIndex: 'userId',
      align: 'center',
    },
    {
      title: '员工名称',
      dataIndex: 'userName',
      align: 'center',
    },
    {
      title: '正常',
      dataIndex: 'workTime',
      align: 'right',
      summary: true,
    },

    {
      title: '正常金额',
      dataIndex: 'workCost',
      align: 'right',
      summary: true,
    },

    {
      title: '平常',
      dataIndex: 'common',
      align: 'right',
      summary: true,
    },
    {
      title: '平常金额',
      dataIndex: 'commonCost',
      align: 'right',
      summary: true,
    },

    {
      title: '公休工时',
      dataIndex: 'workOverTime',
      align: 'right',
      summary: true,
    },
    {
      title: '公休金额',
      dataIndex: 'workOverCost',
      align: 'right',
      summary: true,
    },

    {
      title: '节假',
      dataIndex: 'holiday',
      align: 'right',
      summary: true,
    },
    {
      title: '节假金额',
      dataIndex: 'holidayCost',
      align: 'right',
      summary: true,
    },
    {
      title: '调休/旷工',
      dataIndex: 'deduct',
      align: 'right',
      summary: true,
    },
    {
      title: '调休/旷工费用',
      dataIndex: 'deductCost',
      align: 'right',
      summary: true,
      width: 200,
    },

    {
      title: '工单编码',
      dataIndex: 'baseEntry',
      align: 'center',
    },
    {
      title: '行状态',
      dataIndex: 'lineStatus',
      align: 'center',
    },
  ]);
  const tableLoading = ref(false);
  const formRef = ref(null);

  function init() {
    if (route.query.type === 'info') {
      data.form.docEntry = route.query.docEntry;
      queryData();
    } else {
      data.form.edit = true;
    }
  }

  onMounted(init);

  function back() {
    router.push({ path: '/erp/account' });
  }

  function add() {
    data.form.objId = 78;
    data.form.objName = '日历';
    data.form.docStatus = 'O';
    data.form.approved = false;
    data.form.absId = null;
    data.form.deptId = null;
    data.form.deptName = null;
    data.form.remark = null;
    data.form.edit = true;
    data.form.lista = [];
    router.push({ path: '/erp/accounta', query: { type: 'new', docEntry: null } });
  }

  function save() {
    formRef.value
      .validate()
      .then(() => {
        tableLoading.value = true;
        if (data.form.docEntry) {
          accountApi.update(data.form).then((res) => {
            queryData(data.form.docEntry);
            message.success('修改成功！');
          });
        } else {
          accountApi.add(data.form).then((res) => {
            data.form.docEntry = res.data;
            message.success('保存成功！');
            router.push({ path: '/erp/accounta', query: { type: 'info', docEntry: res.data } });
            queryData(res.data);
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  function edit() {
    data.form.edit = true;
    data.form.lista.forEach((item) => {
      item.edit = true;
    });
  }

  // 更多操作
  function more({ key }) {
    // 审核处理函数
    if (key === 'a') {
      data.form.docStatus = 'C';
      tableLoading.value = true;
      accountApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'b') {
      data.form.docStatus = 'O';
      tableLoading.value = true;
      accountApi.update(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'c') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'A',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'd') {
      approvordApi
        .add({
          docEntry: 0,
          approvLineNum: 2,
          approvType: 'B',
          baseEntry: data.form.docEntry,
          tabName: data.form.objName,
          docStatus: 'O',
          tabId: data.form.objId,
          baseVersion: data.form.version,
        })
        .then((res) => {
          queryData();
        });
    } else if (key === 'e') {
      tableLoading.value = true;
      accountApi.batchExcute(data.form).then((res) => {
        tableLoading.value = false;
        queryData();
      });
    } else if (key === 'f') {
      accountApi.clear(data.form.docEntry).then((res) => {
        queryData();
      });
    }
  }

  function del() {
    Modal.confirm({
      content: `确认删除（${data.form.docEntry}）`,
      onOk() {
        accountApi.delete(data.form.docEntry).then((res) => {
          message.success('删除成功！');
          router.push({ path: '/erp/account' });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }

  async function queryData() {
    tableLoading.value = true;
    formRef.value.resetFields();
    accountApi
      .info(data.form.docEntry)
      .then((res) => {
        data.form = res.data;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  }

  function refresh() {
    queryData();
  }

  function change(item, key) {
    data.form.deptName = key;
  }

  // 审核------------------------------------------------------------------------------------------------
  function approved() {
    data.approvedData.baseEntry = data.form.docEntry;
    data.approvedData.tabName = data.form.objName;
    data.visible.approvord = true;
  }

  function onclose() {
    data.visible.approvord = false;
    queryData();
  }

  function oncloseMmord(item) {
    tableLoading.value = true;
    data.visible.mmord = false;
    if (item.length > 0) {
    } else {
      tableLoading.value = false;
    }
  }

  const combinedNumsa = computed(() => (field) => {
    return data.form.lista.reduce((prev, next) => {
      return prev + next[field];
    }, 0);
  });
  const combinedNumsb = computed(() => (field) => {
    return data.form.listb.reduce((prev, next) => {
      return prev + next[field];
    }, 0);
  });
  const combinedNumsc = computed(() => (field) => {
    return data.form.listc.reduce((prev, next) => {
      return prev + next[field];
    }, 0);
  });
</script>
